package org.outlook.apps.goal.action;

import java.util.Iterator;
import java.util.Vector;

import org.outlook.apps.goal.db.DataSourceService;
import org.outlook.commons.authentocate.LoginEvent;
import org.outlook.commons.authentocate.LoginListener;
import org.outlook.commons.pojo.Config;
import org.outlook.commons.pojo.Globals;

@SuppressWarnings("unchecked")
public class Authenticater {
    private Vector<LoginListener> listenerList = new Vector<LoginListener>();

	public static boolean isRequireLogin() {
		return Config.requireLogin;
	}

	public void addLoginListener(LoginListener listener) {
        listenerList.add(listener);
	}
    
    /**
     * Removes a <strong>LoginListener</strong> from the list of listeners
     *
     * @param listener listener
     */
    public void removeLoginListener(LoginListener listener) {
        listenerList.remove(listener);
    }

	public boolean authenticate(String username, String password, String string) {
		DataSourceService dbService = Globals.dbService;
		if(dbService.authenticate(username, password)) {
			fireLoginSucceeded(new LoginEvent(this));
			return true;
		} else {
			fireLoginFailed(new LoginEvent(this));
			return false;
		}
	}

	void fireLoginStarted(final LoginEvent source) {
        Iterator iter = listenerList.iterator();
        while (iter.hasNext()) {
            LoginListener listener = (LoginListener) iter.next();
            listener.loginStarted(source);
        }
    }

    void fireLoginSucceeded(final LoginEvent source) {
        Iterator iter = listenerList.iterator();
        while (iter.hasNext()) {
            LoginListener listener = (LoginListener) iter.next();
            listener.loginSucceeded(source);
        }
    }
    
    void fireLoginFailed(final LoginEvent source) {
        Iterator iter = listenerList.iterator();
        while (iter.hasNext()) {
            LoginListener listener = (LoginListener) iter.next();
            listener.loginFailed(source);
        }
    }
    
    void fireLoginCanceled(final LoginEvent source) {
        Iterator iter = listenerList.iterator();
        while (iter.hasNext()) {
            LoginListener listener = (LoginListener) iter.next();
            listener.loginCanceled(source);
        }
    }

}
